package com.malex.mxtracker.component;

import com.malex.mxtracker.MxTracker;
import com.malex.mxtracker.bean.Bank;
import com.malex.mxtracker.bean.DataPackage;
import com.malex.mxtracker.bean.Operation;
import com.malex.mxtracker.bean.Project;
import org.apache.wicket.markup.html.WebPage;
import org.codehaus.jackson.map.ObjectMapper;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Properties;


/**
 * Страница создания бекапа базы
 *
 * @author Manusovich Alexander
 */
public class BackupPage extends WebPage {
    public BackupPage() throws UnsupportedEncodingException, MessagingException {
        DataPackage data = new DataPackage();
        data.setBanks(new ArrayList<Bank>(MxTracker.getBanks().values()));
        data.setOperations(new ArrayList<Operation>());
        data.setProjects(new ArrayList<Project>(MxTracker.getProjects().values()));
        StringWriter writer = new StringWriter();
        try {
            ObjectMapper jsonObjectMapper = new ObjectMapper();
            jsonObjectMapper.writeValue(writer, data);
        } catch (IOException e) {
            e.printStackTrace();
        }

        Properties props = new Properties();
        Session session = Session.getDefaultInstance(props, null);

        Message msg = new MimeMessage(session);
        String dateString = new SimpleDateFormat("dd.MM.yyyy").format(new Date());
        msg.setFrom(new InternetAddress("manusovich.mobile@gmail.com", "mxTracker"));
        msg.addRecipient(Message.RecipientType.TO,
                new InternetAddress("manusovich@gmail.com", "Manusovich Alexander"));
        msg.setSubject("mxTracker Backup - " + dateString);
        msg.setText(writer.toString());
        Transport.send(msg);
    }
}